package cn.ly817.jay.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * Created by LuoYu on 2016/12/6.
 */
public class MD5 {
    public static String encrypt(String msg, String charsetName) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        byte[] byteArray = null;
        MessageDigest md5 = null;
        String secret = "";
        md5 = MessageDigest.getInstance("MD5");
        byteArray = md5.digest(msg.getBytes(charsetName));
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        secret = md5StrBuff.toString();
        return secret;
    }

    public static String encrypt(String msg) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        return encrypt(msg, "utf-8");
    }
}
